package com.inepex.inechart.client.linechart;

import java.util.ArrayList;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.inepex.inechart.shared.linechart.Curve;
import com.inepex.inegraphics.impl.client.IncrementalProgress.IncrementalProgressCaller;

public abstract class IncrementalLineChartPointCalculator implements IncrementalProgressCaller {

	protected int partTreshold;
	protected int finishedCurveIndex = -1;
	protected ArrayList<Curve> curves;
	protected LineChartModelAssistGWT target;
	protected double from, to;

	public IncrementalLineChartPointCalculator(int partTreshold, ArrayList<Curve> curves,
			LineChartGwt lineChartGwt, double from, double to) {
		this.from = from;
		this.to = to;
		this.partTreshold = partTreshold;
		this.curves = curves;
		target = lineChartGwt.lineChartModelAssist;
		startCalculating();
	}

	protected void startCalculating(){
		if(nextCurve()){
			Scheduler.get().scheduleIncremental(new RepeatingCommand() {

				@Override
				public boolean execute() {
					boolean inProgress = IncrementalLineChartPointCalculator.this.target.nextProgressPart();
					if(!inProgress){
						inProgress = nextCurve();
						if(!inProgress){
							onFinished();					
						}
					}
					return inProgress;				
				}
			});
		}
	}

	protected boolean nextCurve(){
		if(finishedCurveIndex++ >= curves.size() - 1){
			return false;
		}
		Curve act = curves.get(finishedCurveIndex);
		target.setCurve(act, from, to);
		target.initProgress(this);
		return true;
	}

	@Override
	public int getProgressPartTresholdMS() {
		return partTreshold;
	}

	public abstract void onFinished();

}
